Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hotfix(katana): make sure validator state is synced with block producer #2353

Merged
merged 10 commits into from
Aug 28, 2024

Conversation

kariy
Copy link
Member

@kariy kariy commented Aug 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced concurrency control for block production and transaction validation, improving overall performance and safety.
    • Introduced a new structure for managing validator state, allowing for better organization and encapsulation.
  • Bug Fixes

    • Improved error handling during block production and transaction validation, ensuring more reliable processing.
  • Tests

    • Updated tests to reflect changes in block production and transaction validation structures, ensuring comprehensive coverage of new functionalities.
  • Chores

    • Streamlined code by removing redundant components and optimizing state management across various modules.

Copy link

coderabbitai bot commented Aug 28, 2024

Walkthrough

Ohayo, sensei! The recent changes involve substantial restructuring of the BlockProducer and TxValidator components in the Katana framework. Key modifications include the removal of certain fields for improved concurrency, encapsulation of validator state, and updates to method signatures and return types to enhance clarity. Several files have been updated to reflect these structural changes, ensuring better integration and streamlined functionality.

Changes

File(s) Change Summary
crates/katana/core/src/service/block_producer.rs, mod.rs Removed the validator field from BlockProducer, added a permit field for concurrency control. Updated methods to encapsulate TxValidator within IntervalBlockProducer and InstantBlockProducer structs.
crates/katana/pool/src/validation/stateful.rs Encapsulated TxValidator state in an Inner struct, simplifying state management and locking mechanism. Updated constructor and methods to reflect the new structure.
crates/katana/executor/Cargo.toml Updated blockifier crate branch from cairo-2.7-new to cairo-2.7-newer.
crates/katana/node/src/lib.rs Integrated TxValidator into the transaction pool and RPC server. Updated start and spawn function signatures to include the new validator.
crates/katana/pool/src/pool.rs Modified logging for ValidationOutcome to simplify messages and added logging for dependent transactions.
crates/katana/rpc/rpc/src/starknet/mod.rs Added TxValidator to the Inner struct of StarknetApi, updating the constructor to initialize it. Enhanced nonce retrieval logic to use the validator directly.
crates/katana/rpc/rpc/src/starknet/write.rs Improved error handling in the add_transaction method by implementing error logging.
crates/katana/rpc/rpc/tests/starknet.rs Renamed rapid_transactions_submissions to concurrent_transactions_submissions, enhanced the test for concurrent transaction submissions using tokio::sync, and increased the number of transactions from 10 to 100.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant TransactionPool
    participant Validator
    participant StarknetApi

    User->>TransactionPool: Submit Transaction
    TransactionPool->>Validator: Validate Transaction
    Validator-->>TransactionPool: Validation Result
    TransactionPool-->>User: Transaction Status
Loading
sequenceDiagram
    participant NodeService
    participant BlockProducer
    participant TxValidator

    NodeService->>BlockProducer: Update Block
    BlockProducer->>TxValidator: Validate Transactions
    TxValidator-->>BlockProducer: Validation Result
    BlockProducer-->>NodeService: Block Update Confirmation
Loading

Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 646205d and 0147378.

Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
Files selected for processing (2)
  • crates/katana/core/src/service/block_producer.rs (17 hunks)
  • crates/katana/pool/src/validation/stateful.rs (6 hunks)
Additional comments not posted (10)
crates/katana/pool/src/validation/stateful.rs (5)

27-28: LGTM!

The encapsulation of the internal state using Arc<Inner> is a good design choice for concurrency.

The code changes are approved.


30-34: LGTM!

The struct definition is correct. The use of Mutex for validator and permit for concurrency control is appropriate.

The code changes are approved.


43-53: LGTM!

The constructor method correctly initializes the inner field. The use of Arc and Mutex is appropriate for concurrency control.

The code changes are approved.


58-64: LGTM!

The method correctly updates the validator state. The use of Mutex for locking is appropriate. The transition to new_inner method for state update is a good design choice.

The code changes are approved.


85-97: LGTM!

The methods correctly initialize the StatefulValidatorAdapter. The use of CachedState enhances encapsulation and state management.

The code changes are approved.

crates/katana/core/src/service/block_producer.rs (5)

64-64: LGTM!

The update enhances error handling by wrapping the result in a Result type.

The code changes are approved.


83-98: LGTM!

The methods correctly initialize the producer field with the appropriate mode. The changes are consistent with the new structure.

The code changes are approved.


109-114: LGTM!

The method correctly returns a clone of the validator from the BlockProducerMode. The changes are consistent with the new structure.

The code changes are approved.


Line range hint 199-236: LGTM!

The method correctly initializes the permit and validator fields. The use of Arc and Mutex is appropriate for concurrency control.

The code changes are approved.


Line range hint 502-527: LGTM!

The method correctly initializes the permit and validator fields. The use of Arc and Mutex is appropriate for concurrency control.

The code changes are approved.


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

crates/katana/rpc/rpc/tests/starknet.rs Show resolved Hide resolved
Comment on lines +244 to +259
let account = Arc::new(sequencer.account());

// setup test contract to interact with.
abigen_legacy!(Contract, "crates/katana/rpc/rpc/tests/test_data/erc20.json");
let contract = Contract::new(DEFAULT_FEE_TOKEN_ADDRESS.into(), &account);

// function call params
let recipient = Felt::ONE;
let amount = Uint256 { low: Felt::ONE, high: Felt::ZERO };

const N: usize = 10;
let mut txs = IndexSet::with_capacity(N);
let initial_nonce =
provider.get_nonce(BlockId::Tag(BlockTag::Pending), sequencer.account().address()).await?;

const N: usize = 100;
let nonce = Arc::new(Mutex::new(initial_nonce));
let txs = Arc::new(Mutex::new(IndexSet::with_capacity(N)));

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohayo sensei! Use tokio::sync::RwLock for better read performance.

Consider using tokio::sync::RwLock instead of Mutex for nonce and txs to improve read performance, as multiple reads can occur concurrently without blocking each other.

Apply this diff to use RwLock:

-use tokio::sync::Mutex;
+use tokio::sync::{Mutex, RwLock};

-let nonce = Arc::new(Mutex::new(initial_nonce));
-let txs = Arc::new(Mutex::new(IndexSet::with_capacity(N)));
+let nonce = Arc::new(RwLock::new(initial_nonce));
+let txs = Arc::new(RwLock::new(IndexSet::with_capacity(N)));
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let account = Arc::new(sequencer.account());
// setup test contract to interact with.
abigen_legacy!(Contract, "crates/katana/rpc/rpc/tests/test_data/erc20.json");
let contract = Contract::new(DEFAULT_FEE_TOKEN_ADDRESS.into(), &account);
// function call params
let recipient = Felt::ONE;
let amount = Uint256 { low: Felt::ONE, high: Felt::ZERO };
const N: usize = 10;
let mut txs = IndexSet::with_capacity(N);
let initial_nonce =
provider.get_nonce(BlockId::Tag(BlockTag::Pending), sequencer.account().address()).await?;
const N: usize = 100;
let nonce = Arc::new(Mutex::new(initial_nonce));
let txs = Arc::new(Mutex::new(IndexSet::with_capacity(N)));
let account = Arc::new(sequencer.account());
// setup test contract to interact with.
abigen_legacy!(Contract, "crates/katana/rpc/rpc/tests/test_data/erc20.json");
// function call params
let recipient = Felt::ONE;
let amount = Uint256 { low: Felt::ONE, high: Felt::ZERO };
let initial_nonce =
provider.get_nonce(BlockId::Tag(BlockTag::Pending), sequencer.account().address()).await?;
const N: usize = 100;
let nonce = Arc::new(RwLock::new(initial_nonce));
let txs = Arc::new(RwLock::new(IndexSet::with_capacity(N)));

Copy link

codecov bot commented Aug 28, 2024

Codecov Report

Attention: Patch coverage is 93.79310% with 9 lines in your changes missing coverage. Please review.

Project coverage is 67.56%. Comparing base (f9606d8) to head (0147378).
Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
crates/katana/core/src/service/block_producer.rs 90.72% 9 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2353      +/-   ##
==========================================
+ Coverage   67.27%   67.56%   +0.29%     
==========================================
  Files         357      359       +2     
  Lines       46649    46960     +311     
==========================================
+ Hits        31383    31729     +346     
+ Misses      15266    15231      -35     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Collaborator

@glihm glihm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀

@glihm glihm merged commit 76dae5e into main Aug 28, 2024
15 checks passed
@glihm glihm deleted the katana/validator-sync branch August 28, 2024 16:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants